package me.shurufa.activities;

import android.annotation.TargetApi;
import android.content.Intent;
import android.content.res.AssetFileDescriptor;
import android.graphics.Bitmap;
import android.hardware.Camera;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Vibrator;
import android.util.DisplayMetrics;
import android.view.KeyEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceHolder.Callback;
import android.view.SurfaceView;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.Result;

import java.io.IOException;
import java.util.Vector;

import butterknife.Bind;
import me.shurufa.R;
import me.shurufa.testactivities.TestQRScanResultActivity;
import me.shurufa.utils.Constants;
import me.shurufa.utils.StatusBarCompat;
import me.shurufa.widget.simpledialog.SimpleDialog;
import me.shurufa.zxing.camera.CameraManager;
import me.shurufa.zxing.decoding.CaptureActivityHandler;
import me.shurufa.zxing.decoding.InactivityTimer;
import me.shurufa.zxing.view.ViewfinderView;

/**
 * Created by wangsongyan
 * Email: wangsongyan@shandianshua.com
 */
public class QRScanActivity extends BaseActivity implements Callback, View.OnClickListener {


    @Bind(R.id.close_scan)
    RelativeLayout closeScan;
    private CaptureActivityHandler handler;

    @Bind(R.id.viewfinder_view)
    ViewfinderView viewfinderView;

    private boolean hasSurface;
    private Vector<BarcodeFormat> decodeFormats;
    private String characterSet;
    private InactivityTimer inactivityTimer;
    private MediaPlayer mediaPlayer;
    private boolean playBeep;
    private static final float BEEP_VOLUME = 0.10f;
    private boolean vibrate;
    public static int RESULT_CODE = 999;
    public boolean fromCamera;

    @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
    @Override
    public void onCreate(Bundle savedInstanceState) {
        try {
            this.requestWindowFeature(Window.FEATURE_NO_TITLE);
            getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
            activity_layout_res = R.layout.activity_capture;
            super.onCreate(savedInstanceState);
            fromCamera = getIntent().getBooleanExtra(Constants.EXTRA_FROM_CAMERA, false);
            DisplayMetrics dm = new DisplayMetrics();
            getWindowManager().getDefaultDisplay().getRealMetrics(dm);
            // 扫描框的边长
            int length = (dm.widthPixels * 2) / 3;

            // ViewUtil.addTopView(getApplicationContext(), this, R.string.scan_card);
            CameraManager.init(getApplication(), length);
            hasSurface = false;
            inactivityTimer = new InactivityTimer(this);
            closeScan.setOnClickListener(this);
        } catch (Exception e) {
            showFinishDlg();
        }
    }

    @Override
    public void initStatusBar() {
        try {
            StatusBarCompat.setTranslucent(this, 0);
        } catch (Exception e) {
            showFinishDlg();
        }
    }

    @Override
    protected void onResume() {
        try {
            super.onResume();

            // 校验相机是否会因为权限问题而崩溃
            Camera c = Camera.open();
            if (c == null) {
                showFinishDlg();
                return;
            } else {
                c.release();
            }


            SurfaceView surfaceView = (SurfaceView) findViewById(R.id.preview_view);
            SurfaceHolder surfaceHolder = surfaceView.getHolder();
            if (hasSurface) {
                initCamera(surfaceHolder);
            } else {
                surfaceHolder.addCallback(this);
                surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
            }
            decodeFormats = null;
            characterSet = null;

            playBeep = true;
            AudioManager audioService = (AudioManager) getSystemService(AUDIO_SERVICE);
            if (audioService.getRingerMode() != AudioManager.RINGER_MODE_NORMAL) {
                playBeep = false;
            }
            initBeepSound();
            vibrate = true;
        } catch (Exception e) {
            showFinishDlg();
        }
    }

    @Override
    protected void onPause() {
        try {
            super.onPause();
            if (handler != null) {
                handler.quitSynchronously();
                handler = null;
            }
            CameraManager.get().closeDriver();
        } catch (Exception e) {
            showFinishDlg();
        }
    }

    @Override
    protected void onDestroy() {
        try {
            inactivityTimer.shutdown();
            super.onDestroy();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void handleDecode(Result result, Bitmap barcode) {
        inactivityTimer.onActivity();
        playBeepSoundAndVibrate();
        String resultString = result.getText();
        if (resultString.equals("")) {
            Toast.makeText(QRScanActivity.this, getString(R.string.scan_failed), Toast.LENGTH_SHORT).show();
        } else {
            if (fromCamera) {
                //TODO 如果是从相机跳转来的页面 扫描后要跳转至其他页面
                Intent intent = new Intent(QRScanActivity.this, TestQRScanResultActivity.class);
                intent.putExtra(Constants.EXTRA_SCAN_RESULT, resultString);
                startActivity(intent);
                finish();
            } else {
                Intent resultIntent = new Intent();
                Bundle bundle = new Bundle();
                bundle.putString(Constants.EXTRA_SCAN_RESULT, resultString);
                resultIntent.putExtras(bundle);
                this.setResult(RESULT_CODE, resultIntent);
            }
        }
        QRScanActivity.this.finish();
    }

    private void initCamera(SurfaceHolder surfaceHolder) {
        try {
            CameraManager.get().openDriver(surfaceHolder);
        } catch (IOException ioe) {
            return;
        } catch (RuntimeException e) {
            showFinishDlg();
            return;
        }
        if (handler == null) {
            handler = new CaptureActivityHandler(this, decodeFormats,
                    characterSet);
        }
    }

    private void showFinishDlg() {
        SimpleDialog dialog = new SimpleDialog(this);
        dialog.setNegativeButtonVisibility(View.GONE)
                .setContentText(getString(R.string.cannot_open_camera))
                .setOnPositiveListener(R.string.commit, new SimpleDialog.OnPositiveListener() {
                    @Override
                    public void onClick(SimpleDialog dialog) {
                        QRScanActivity.this.finish();
                        dialog.dismiss();
                    }
                })
                .show();
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width,
                               int height) {

    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        if (!hasSurface) {
            hasSurface = true;
            initCamera(holder);
        }

    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        hasSurface = false;

    }

    public ViewfinderView getViewfinderView() {
        return viewfinderView;
    }

    public Handler getHandler() {
        return handler;
    }

    public void drawViewfinder() {
        viewfinderView.drawViewfinder();
    }

    private void initBeepSound() {
        if (playBeep && mediaPlayer == null) {
            // The volume on STREAM_SYSTEM is not adjustable, and users found it
            // too loud,
            // so we now play on the music stream.
            setVolumeControlStream(AudioManager.STREAM_MUSIC);
            mediaPlayer = new MediaPlayer();
            mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            mediaPlayer.setOnCompletionListener(beepListener);

            AssetFileDescriptor file = getResources().openRawResourceFd(
                    R.raw.beep);
            try {
                mediaPlayer.setDataSource(file.getFileDescriptor(),
                        file.getStartOffset(), file.getLength());
                file.close();
                mediaPlayer.setVolume(BEEP_VOLUME, BEEP_VOLUME);
                mediaPlayer.prepare();
            } catch (IOException e) {
                mediaPlayer = null;
            }
        }
    }

    private static final long VIBRATE_DURATION = 200L;

    private void playBeepSoundAndVibrate() {
        if (playBeep && mediaPlayer != null) {
            mediaPlayer.start();
        }
        if (vibrate) {
            Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
            vibrator.vibrate(VIBRATE_DURATION);
        }
    }

    /**
     * When the beep has finished playing, rewind to queue up another one.
     */
    private final OnCompletionListener beepListener = new OnCompletionListener() {
        public void onCompletion(MediaPlayer mediaPlayer) {
            mediaPlayer.seekTo(0);
        }
    };

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.close_scan:
                try {
                    if (handler != null) {
                        handler.quitSynchronously();
                        handler = null;
                    }
                    CameraManager.get().closeDriver();
                } catch (Exception e) {
                } finally {
                    finish();
                }
                break;
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            try {
                CameraManager.get().closeDriver();
            } catch (Exception e) {
            } finally {
                finish();
            }
        }
        return false;
    }
}
